'use strict';

/* Controllers */
app.controller('houseOwnerLoanListCtl', function($scope,$compile,ngDialog,uiLoad,rest,$ocLazyLoad,$state,user,$http) {
    var rentTypeObj = {
        0: "年付",
        1: "季付",
        2: "月付"
    };
    var applyTypeObj = {
        0: "支付包",
        1: "微信",
        2: "现金"
    };
    $scope.checkType = {};
    $scope.checkStatus = {};
    $scope.checkTypeArray = [{ "name": "全部", "value": "" }, 
                             { "name": "申请中", "value": "0" }, 
                             { "name": "申请通过", "value": "1" }, 
                             { "name": "申请不通过", "value": "2" }, 
                             // { "name": "装修中", "value": "3" }, 
                             // { "name": "装修完成", "value": "4" }
                             ];
    if($scope.queryParams){

    }
    $scope.queryParams = {
        'checkStatus': $scope.checkStatus.selected,
        'contractStartDate': $scope.contractStartDate,
        'contractEndDate': $scope.contractEndDate,
        'nameCode': $scope.nameCode
    }

    $scope.$watch('nameCode', function(newValue, oldValue) {
         $scope.nameCode = newValue;
    })
    $scope.$on('contractDate.start', function(event, data) {
        $scope.contractStartDate = data ? (data + " 00:00:00") : "";
        console.log(data);
    });
    $scope.$on('contractDate.end', function(event, data) {
        $scope.contractEndDate = data ? (data + " 00:00:00") : "";
        console.log(data);
    });
    $scope.queryUser = function() {
        if($scope.queryParams.checkStatus && $scope.queryParams.checkStatus.selected){
            var checkStatusCache = $scope.queryParams.checkStatus.selected;
            if($scope.queryParams.checkStatus.selected){
                $scope.queryParams.checkStatus = $scope.queryParams.checkStatus.selected.value
            }
            $scope.queryParams = {
              //'checkStatus': $scope.checkStatus.selected,
                'contractStartDate': $scope.contractStartDate,
                'contractEndDate': $scope.contractEndDate,
                'nameCode': $scope.nameCode
            }
            console.log($scope.queryParams);
            $scope.dataTable.fnClearTable();
            $scope.queryParams.checkStatus = {};
            $scope.queryParams.checkStatus.selected = {};
            $scope.queryParams.checkStatus.selected = decorateStatusCache;
        }else{
            $scope.queryParams = {
               // 'checkStatus': $scope.decorateStatus.selected,
                'contractStartDate': $scope.contractStartDate,
                'contractEndDate': $scope.contractEndDate,
                'nameCode': $scope.nameCode
            }
            console.log($scope.queryParams);
            $scope.dataTable.fnClearTable();
        }
    };
    $scope.tableLoanDatas = {
        "sAjaxSource": "4011",
        "aoColumns": [{
            "mDataProp": "checkStatusName",
            "sTitle": "审核状态",
            "sDefaultContent": "",
            "sClass": "center audit"
        }, 
        {
            "mDataProp": "",
            "sTitle": "序号",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": "cityName",
            "sTitle": "城市",
            "sDefaultContent": "",
            "sClass": "center"
        }, 
        // {
        //     "mDataProp": "countyName",
        //     "sTitle": "区县",
        //     "sDefaultContent": "",
        //     "sClass": "center"
        // }, 
        {
            "mDataProp": "areaName",
            "sTitle": "小区名称",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "leaseType",
            "sTitle": "出租类型",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "houseType",
            "sTitle": "户型",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "",
            "sTitle": "门牌号",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "payTypeName",
            "sTitle": "支付方式",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "createDate",
            "sTitle": "提交时间",
            "sDefaultContent": "",
            "sClass": "center submit-time"
        }, {
            "mDataProp": "checkDate",
            "sTitle": "审核时间",
            "sDefaultContent": "",
            "sClass": "center checkout-time"
        // 小艳说：提现额度隐藏，以后要有一个提现额度总值
        // }, {
        //     "mDataProp": "assessAmount",
        //     "sTitle": "提现额度",
        //     "sDefaultContent": "",
        //     "sClass": "center"
        }, {
            "mDataProp": "",
            "sTitle": "锁电安装状态",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": "operate",
            "sTitle": "操作",
            "sDefaultContent": "",
            "sClass": "center handle-td operation"
        }],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            var btnStr = "";
            var auditStr = "";
            if ("0" == aData.checkStatus) {
                auditStr = "<div><div class='rent-bj1'>申请中</div><div class='rent-bj'></div></div>"
            } 
            if ("1" == aData.checkStatus) {             
                auditStr = "<div><div class='confirmed-bj1'>申请成功</div><div class='confirmed-bj status-num4'></div></div>"
            }
            if ("2" == aData.checkStatus) {
                auditStr = "<div><div class='failure-bj1'>申请失败</div><div class='failure-bj status-num4'></div></div>"
            }

            // 查看 一直在，始终能看
            //  btnStr = $('<div></div>').append(row_audit_staus(aData)).html();

            //  function row_audit_staus (data) {



            //     var sdom = $('<a></a>').addClass('operation-btn');
            //     var simg = $('<img>').attr({
            //         'src': 'img/operation.png',
            //         'width': '20px',
            //         'height': '20px'
            //     });
            //     var sdiv = $('<div></div>').addClass('operation-loan');
            //     var sdl = $('<dl></dl>').addClass('operation oper-triangle');
            //     var sdd = $('<dd></dd>');
            //     if (aData.checkStatus == "2") {
            //         var shref_1 = $('<a>修改</a>').attr({
            //             'ng-click':'decorateModify($event, \"' + aData.decorateId + '\")',
            //         });
            //     }else{
            //         var shref_1 = $('<a>查看</a>').attr({
            //             'ng-click':'decorateReview($event, \"' + aData.decorateId + '\")',
            //         });
            //     };
            //     var sdd_1 = $('<dd></dd>'),shref_2;
            //     if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
            //             // 申请装修分期(灰)：装修评估申请中
            //         // shref_2 = $('<div>申请装修分期</div>');
            //     }else if("4" == aData.decorateStatus && "0" == aData.decorateOrderStatus) {
            //             // 申请装修分期：锁电安装完成
            //         shref_2 = $('<a>申请装修分期</a>').attr({
            //             'ng-click':'decorateWithdraw($event, \"" + aData.decorateId + "\")',
            //         });
            //     } else if("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
            //            // 授信冻结(灰)：申请通过
            //         shref_2 = $('<div>授信冻结</div>');
            //     }else if("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
            //            // 授信冻结(灰)：申请通过
            //         shref_2 = $('<div>授信冻结</div>');
            //     }else if("1" == aData.decorateOrderStatus) {
            //            // 分期业务申请中：（提现中）申请装修分期确认
            //         shref_2 = $('<div>分期业务申请中</div>');
            //     }else if("2" == aData.decorateOrderStatus) {
            //            // 分期业务申请中：（提现中）申请装修分期确认
            //         shref_2 = $('<div>申请通过</div>');
            //     }else {
            //         // 未知状态
            //     }
            //     var sdd_2 = $('<dd></dd>');
            //     var span = $('<span>◆</span>').addClass('z-1');
            //     var span_1 = $('<span>◆</span>').addClass('y-1');

            //     sdd_2.append(span_1).append(span)
            //     sdd_1.append(shref_2)
            //     sdd.append(shref_1)
            //     sdl.append(sdd).append(sdd_1).append(sdd_2)
            //     sdiv.append(sdl)
            //     sdom.append(simg).append(sdiv)
            //     return sdom;
            // }

            
             //btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";

            // 装修评估资料
            // 能改 2(申请不通过)
            // 不能改 0(申请中)，1(申请通过)
            
            if( aData.checkStatus == "2") {
                 btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateModify($event, \"" + aData.decorateId + "\")'>修改</a>";
                } 
                else {
                  btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                }
            // 装修分期
            // 申请装修分期(灰)：装修评估申请中
            // 授信冻结(灰)：申请通过
            // 申请装修分期：锁电安装完成
            // 分期业务申请中：（提现中）申请装修分期确认
            // 驳回：金融业务驳回

            // decorateOrderStatus
            // 0，平时，未进入分期业务申请
            // 1，表示分期业务申请中
            // 2，表示申请通过
            // 3，表示申请未通过
            // 4，表示还款中
            // 5，表示订单完结

            if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //申请装修分期(灰)：装修评估申请中
                btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>申请装修分期</a>";
            } else if ("4" == aData.decorateStatus && "0" == aData.decorateOrderStatus) {
                // 申请装修分期：锁电安装完成
                btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateWithdraw($event, \"" + aData.decorateId + "\")'>申请装修分期</a>";
            } else if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                // 授信冻结(灰)：申请通过
                btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>授信冻结</a>";
            } else if ("1" == aData.decorateOrderStatus) {
                // 分期业务申请中：（提现中）申请装修分期确认
                btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>分期业务申请中</a>";
            } else if ("2" == aData.decorateOrderStatus) {
                // 分期业务申请中：（提现中）申请装修分期确认
                btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>申请通过</a>";
            } else {
                // 未知状态
                btnStr += "";
            }

            

            function time(mydate){
              var str = mydate.substring(0,10);
              var dataArr = str.split('-');
              var timeStr = dataArr[0]
                +"年"+dataArr[1]+"月"+dataArr[2]
                +"日";
                return timeStr;
            }
            // btnStr += "<a href='javascript:;' class='btn btn-yellow' ng-click='cancelReturnProOrder(" + aData.houseId + "," + aData.orderId +")' style='margin-right:10px;' >补件</a>";
            $(nRow).find(".handle-td").append($compile(btnStr)($scope));
            $(nRow).find(".handle-td>a.operation-btn").on('click', function (e) {
                e.preventDefault();
                var sopt = $(this).parent().find(".operation-loan");
                if (sopt.css('display') == 'none') {
                    $(".operation-loan").hide();
                    sopt.show();
                } else {
                    sopt.hide();
                }
                return false;
            });              
            $(nRow).find(".submit-time").empty().append(time(aData.createDate));
            $(nRow).find(".checkout-time").empty().append(time(aData.checkDate));
            $(nRow).find(".audit").empty().append($compile(auditStr)($scope));
        },
        "fnDrawCallback": function(oSettings) {
            $scope.checkStatusValue = $scope.queryParams.checkStatus;
            if ("number" == typeof $scope.checkStatusValue) {
                $scope.checkTypeArray.map(function(ele, index) {
                    if ($scope.checkStatusValue == ele.value) {
                        $scope.checkStatus.selected = ele;
                    }
                })
            }
        },
        "fnServerParams": function(aoData) {
            if($scope.checkStatus && $scope.checkStatus.selected){
                $scope.queryParams.checkStatus = $scope.checkStatus.selected.value
            }
            aoData.push({
                'name': 'queryParams',
                'value': $scope.queryParams
            });
            return aoData;
        }
    };
    $scope.dataTable = undefined;

          // "landlordId": "40155814-52b1-4cf2-814a-724f770bbd5b",
          // "decorateId": "5bea9b36-1f94-4bf6-af8a-e2ed3117f53b",
          // "houseId": "e55c6e9f-d6b4-46d0-94c5-e20063ee0611",

    $scope.decorateWithdraw = function (e, decorateId) {
        
        ngDialog.openConfirm({
          template: 'js/module/fund/confirmAgain.html',
          resolve: {
            load: function() {
                return uiLoad.load(['js/module/fund/confirmAgain.js'])
            }
          },
          data:{
            decorateId: decorateId
          },
          scope: $scope,
          width: 600,
          // height: 700
        }).then(null, function(reason) {
            if (reason && reason.clickOk) {
                var btn = $(e.target);
                btn.addClass('disabled');
                rest.post({
                    methodId: '4036',
                    data: {'decorateId': decorateId},
                    success: function(res) {
                        if (res.code == 0) {
                            btn.text('分期业务申请中');
                        } else {
                            btn.removeClass('disabled');
                        }
                    },
                    error: function() {
                        btn.removeClass('disabled');
                    }
                })
            }
        });

        

    }
    $scope.withdrawPrompt = function (e, decorateId) {
    }

    $scope.decorateModify = function (e, decorateId) {
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/modify.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/modify.js'])
                    });
            }
          },
          data:{
            decorateId:decorateId
          },
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
            $state.go('app.houseOwner.loanList');
            btn.text('申请装修分期').addClass("disabled");
            // window.location.reload();
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $state.go('app.houseOwner.loanList');
        });

    }

    $scope.decorateReview = function (e, decorateId) {
        ngDialog.openConfirm({
          template: 'js/module/decorate/review.html',
          resolve: {
            load: function() {
              return uiLoad.load(['js/module/decorate/review.js'])
            }
          },
          data:{
            decorateId:decorateId
          },
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {

        }, function(reason) {

        });
    }

    $scope.loansStr1 = function () {
        ngDialog.openConfirm({
          template: 'js/module/decorate/loans.html',
          resolve: {
            load: function() {
              return uiLoad.load(['js/module/decorate/loans.js'])
            }
          },
          data:{
            
          },
          scope: $scope,
          width: 600,
          // height: 700
        }).then(function(data) {
            
        }, function(reason) {
            console.log('close it');

        });
        // alert("111111111111111111111111111111111");
    }

    // 回调函数,返回实例化的jquery 插件对象
    $scope.initFinish = function(dataTable) {
        $scope.dataTable = dataTable;
    }
    $('#example thead').on('click', 'th', function() {
        // var data = $('#example').DataTable().row( this ).data();
        // alert('You clicked on  row');
    });
    $('#example tbody').on('click', 'span#edit', function() {
        var data = $('#example').DataTable().row($(this).parents('tr'));
        alert("查看修改：" + data[0]);
    });
    $('#example tbody').on('click', 'span#del', function() {
        // var data = $('#example').DataTable().row($(this).parents('tr')).data();
    });
});


app.controller('ContractTimeCtrl',function($scope){
  $scope.today = function() {
      $scope.contractStartDate = "";
      $scope.contractEndDate = "";
    };

    $scope.closeAll = function() {
      $scope.openContractBeginDated =
      $scope.openContractEndDated = false;
    }

    $scope.openContractBeginDate = function($event) {
      $event.preventDefault();$event.stopPropagation();$scope.closeAll();
      $scope.openContractBeginDated = true;
    };
    $scope.openContractEndDate = function($event) {
      $event.preventDefault();$event.stopPropagation();$scope.closeAll();
      $scope.openContractEndDated = true;
    };

    $scope.dateOptions = {
      format: 'yyyy/MM/dd',
      startingDay: 1,
      class: 'datepicker'
    };

    $scope.format = 'yyyy/MM/dd';

    $scope.today();

    $scope.$watch('contractStartDate',function(newValue,oldValue){
      if("[object Date]" === Object.prototype.toString.call(newValue)) {
         $scope.$emit('contractDate.start',moment(newValue).format('YYYY/MM/DD'))
      } else if (null === newValue) {
        $scope.$emit('contractDate.start','')
      }
    });
    $scope.$watch('contractEndDate',function(newValue,oldValue){
      if("[object Date]" === Object.prototype.toString.call(newValue)) {
         $scope.$emit('contractDate.end',moment(newValue).format('YYYY/MM/DD'))
      } else if (null === newValue) {
        $scope.$emit('contractDate.end','')
      }
    });
});
